<template>
    <el-row class="contain-box">
        <site-nav>&emsp;>&emsp;<strong>{{name}}<i> ({{username}})</i></strong></site-nav>
        <div class="view-body">
            <el-row>
                <el-form class="inline-form" inline>
                    <el-form-item>
                        <el-button @click="$back"><i class="el-icon-arrow-left el-icon--left"/>返回</el-button>
                        <el-button @click="addPosition" type="primary"><i class="el-icon-plus el-icon--left"/>添加用户职位
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row>
                <el-col>
                    <el-table :data="list" border>
                        <el-table-column label="部门-职位" prop="department.fullname">
                            <template slot-scope="scope">{{scope.row.department ? scope.row.department.departmentName :
                                ''}} - {{scope.row.duty ? scope.row.duty.dutyName: ''}}
                            </template>
                        </el-table-column>
                        <el-table-column align="left" label="操作">
                            <template slot-scope="scope">
                                <el-button disabled size="mini" type="danger"
                                           v-if="$isManagerDuty(scope.row.dutyId)">部门主管/分管领导职位请在部门管理中进行操作
                                </el-button>
                                <el-button disabled size="mini" type="danger"
                                           v-else-if="$isSystemDuty(scope.row.dutyId)">系统职位无法操作
                                </el-button>
                                <el-button disabled size="mini" type="danger"
                                           v-else-if="scope.row.dutyId === mainDutyId && scope.row.departmentId === departmentId">
                                    主职位无法操作
                                </el-button>
                                <el-button @click="deleteTakeOffice(scope.row)" size="mini" type="danger" v-else>删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <el-row>
                <el-col class="pagination">
                    <el-pagination :current-page="params.pageId" :page-size="params.pageSize" :total="count"
                                   @current-change="currentChange" background layout="total, prev, pager, next"/>
                </el-col>
            </el-row>
        </div>

        <el-dialog :before-close="dialogClose" :title="dialog.isAdd ? '新增用户职位' : '修改用户职位'" :visible.sync="dialog.show"
                   class="dialog">
            <el-form :model="info" :rules="rules" label-width="120px" ref="form" size="small">
                <el-form-item label="部门" prop="departmentId" required>
                    <dept-tree-selecter @change="changeDepartmentId" v-model="info.departmentId"/>
                </el-form-item>
                <el-form-item label="职位" prop="dutyId" required>
                    <el-select clearable filterable placeholder="请选择" v-model="info.dutyId">
                        <el-option :key="item.dutyId" :label="item.dutyName"
                                   :value="item.dutyId" v-for="item in duties" v-if="!dutyFilter(item.dutyId)"/>
                    </el-select>
                </el-form-item>
            </el-form>
            <div class="dialog-footer" slot="footer">
                <el-button @click="dialogClose" size="mini">取 消</el-button>
                <el-button :loading="dialog.submitting" @click="dialogSubmit" size="mini" type="primary">确 定</el-button>
            </div>
        </el-dialog>
    </el-row>
</template>
<script lang="ts">
  import {ID, PARAMS} from '@/api/http';
  import DepartmentApi from '@/api/user/departmentApi';
  import DutyApi from '@/api/user/dutyApi';
  import PositionApi from '@/api/user/positionApi';
  import DialogInfo from '@/structure/dialogInfo';
  import Duty from '@/structure/duty';
  import FormRules from '@/structure/formRules';
  import Position from '@/structure/position';
  import {ElForm} from 'element-ui/types/form';
  import {Component, Vue} from 'vue-property-decorator';

  @Component
  export default class TakeOfficePage extends Vue {
    public duties: Duty[] = [];
    public list: Position[] = [];
    public distribution: ID[] = [];
    public count: number | null = null;
    public userId: ID = 0;
    public dutyId?: ID = null;
    public departmentId: ID = 0;
    public mainDutyId: ID = 0;
    public name: string = '';
    public username: string = '';
    public params: PARAMS = {};
    public dialog: DialogInfo = new DialogInfo();
    public info: Position = new Position();
    public rules: FormRules = {
      departmentId: [
        {
          required: true,
          message: '请选择部门'
        }
      ],
      dutyId: [
        {
          required: true,
          message: '请选择职位'
        }
      ]
    };

    public get form(): ElForm {
      return this.$refs.form as ElForm;
    }

    public created(): void {
      this.userId = this.$route.params.userId;
      this.name = this.$route.query.name as string;
      this.username = this.$route.query.username as string;
      this.departmentId = this.$route.query.departmentId as ID;
      this.mainDutyId = this.$route.query.mainDutyId as ID;
      this.info.userId = this.userId;
      this.info.departmentId = this.departmentId;

      DutyApi.all().then((res) => {
        this.duties = res;
      });

      this.getDataList();
    }

    public changeDepartmentId(departmentId: ID): void {
      if (departmentId === undefined) {
        this.distribution = [];
      } else {
        DepartmentApi.getDistribution(departmentId).then((res) => this.distribution = res);
      }
    }

    public dutyFilter(dutyId: ID): boolean {
      return this.$isSystemDuty(dutyId) || !this.distribution.includes(dutyId);
    }

    public getDataList(): void {
      const params = {
        userId: this.userId,
        ...this.params
      };

      PositionApi.findList(params).then((res) => {
        this.list = res.list;
        this.count = res.count;
      });
    }

    public currentChange(val: number): void {
      this.params.pageId = val;
      this.getDataList();
    }

    public addPosition(): void {
      this.dialog.isAdd = true;
      this.dialog.show = true;

      this.$nextTick(() => {
        this.form.clearValidate();
      });
    }

    public dialogClose() {
      this.dialog.show = false;
      this.form.resetFields();
    }

    public dialogSubmit() {
      if (this.dialog.submitting) {
        return;
      }

      this.form.validate((valid) => {
        if (!valid) {
          return false;
        }

        this.dialog.submitting = true;

        PositionApi.save(this.info).then(() => {
          this.getDataList();
          this.dialogClose();
          this.$message.success('添加用户职位成功');
          this.dialog.submitting = false;
        }).catch(() => {
          this.dialog.submitting = false;
        });
      });
    }

    public deleteTakeOffice(info: Position): void {
      this.$confirm('是否删除该职位?', '删除职位', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        PositionApi.delete(info).then(() => {
          this.getDataList();
          this.$message.success('删除成功!');
        });
      });
    }
  }
</script>
<style lang="scss" scoped>
    .takeoffice-list {
        .green {
            color: #0be841;
        }

        .red {
            color: red;
        }
    }
</style>
